# -*- encoding: utf-8 -*-
'''

Send message using API of work wechat.
Company ID: ww1d726df782afe2ef
Agentid: 1000002
Secret: zxGEelm2ZaC3s04FScAg8tb8235plrkF-aJ5No9eLT0

@File    :   message.py
@Time    :   2021/11/04 16:48:15
@Author  :   Yangshuo He
@Contact :   sugarhe58@gmail.com
'''

import requests
import json

class Message():
    def __init__(self, secret, company_id) -> None:
        self.secret = secret
        self.company_id = company_id
        # self.img_path = img_path
        pass

    def getToken(self):
        url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={}&corpsecret={}"
        get_req = requests.get(url=url.format(self.company_id, self.secret))
        access_token = get_req.json().get('access_token')

        return access_token

    def sendMsg(self, img_path):
        # obtain token using Wechat API
        token = self.getToken()
        url = 'https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={}&type=image'.format(token)

        # obtain image file or image
        files = {"media": ('media', open(img_path, "rb"))}

        # send message
        html = requests.post(url, files=files)
        media_id = html.json()['media_id']
        url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='+token
        data = {
            "touser" : '@all',
            "msgtype" : "image",
            "agentid" : 1000002,
            "image" : {
                    "media_id" : media_id
                }
            }
        html = requests.post(url, data=json.dumps(data))
        err_msg = html.json()['errmsg']

        if err_msg == "ok":
            send_feedback = True
        else:
            send_feedback = False
            
        return send_feedback

if __name__ == '__main__':
    company_id = "ww1d726df782afe2ef"
    secret = "zxGEelm2ZaC3s04FScAg8tb8235plrkF-aJ5No9eLT0"
    img_path = "/home/pi/Pictures/supervise/test.jpg"
    message = Message(secret, company_id)
    feedback = message.sendMsg(img_path)
    if feedback:
        print(">> Send => ok")
    else:
        print("xx Send => failure")
    